package com.dudu.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.IConferenceDialEndService;
import com.dudu.service.IConferenceDialService;
import com.dudu.service.ILogService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.impl.AccountExtendServiceImpl;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.CheckValidityServiceImpl;
import com.dudu.service.impl.ConferenceDialEndServiceImpl;
import com.dudu.service.impl.ConferenceDialServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.PhoneUtils;

import core.CoreService;

/**
 * 点击拨号实现类
 * 
 * @author qinfx
 * @date 2017-4-24
 */
public class OpenAbilityDIALController extends CoreService implements IOpenAbilityDIALController {
    // 用于记录相应接口调用的日志
    private ILogService logService = new LogService();

    // app扩展信息操作
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    private IAccountExtendService accountExtendService = new AccountExtendServiceImpl();
    // 验证信息类
    private ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
    // 运营平台相关操作
    private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();

    /**
     * 发起两人会话
     * 
     * @return
     */
    @Override
    public String dial() {
	log.info("load OpenAbilityDIALController.dial V4 发起多人会话 ");
	// 计算接口调用开始时间
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 发起会议的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 主叫号码
	String caller = this.getRequest().getParameter("caller");
	String[] callerStr = { "caller", caller, "20", "0", "str" };
	checkParamlist.add(callerStr);
	// 被叫号码：以‘,’分割
	String called = this.getRequest().getParameter("called");
	String[] calledStr = { "called", called, "20", "0", "str" };
	checkParamlist.add(calledStr);
	// 是否录音（1:录音，其他：不录音）
	String isRecord = this.getRequest().getParameter("isRecord");
	String[] isRecordStr = { "isRecord", isRecord, "2", "1", "str" };
	checkParamlist.add(isRecordStr);
	if (StringUtils.isBlank(isRecord)) { // 默认不录音
	    isRecord = "";
	}
	// 工作圈适用参数--其它应用不适用
	String callback = this.getRequest().getParameter("callback");
	// 被叫号码显示模式：0为显示配置号码、1为显示主叫号码
	String displayNbrMode = this.getRequest().getParameter("display_mode");
	String[] displayNbrModeStr = { "displayNbrMode", displayNbrMode, "2", "1", "str" };
	checkParamlist.add(displayNbrModeStr);
	// 如果没有传递相应参数，则默认为显号配置号码
	if (StringUtils.isBlank(displayNbrMode)) {
	    displayNbrMode = "1";
	}
	// 来电显示号码（主叫显示号码）可为空，为空循环读取
	String displayNbr = this.getRequest().getParameter("displayNbr");
	String[] displayNbrStr = { "displayNbr", displayNbr, "20", "1", "str" };
	checkParamlist.add(displayNbrStr);
	if (StringUtils.isBlank(displayNbr)) {
	    displayNbr = "";
	}
	// 强制使用平台号码(值为1时，强制使用平台号码发起)
	String usePlatNbr = this.getRequest().getParameter("usePlatNbr");
	String[] usePlatNbrStr = { "usePlatNbr", usePlatNbr, "20", "1", "str" };
	checkParamlist.add(usePlatNbrStr);
	if (StringUtils.isBlank(usePlatNbr) || !"1".equals(usePlatNbr)) { // 不为1时不强制使用平台号
	    usePlatNbr = "";
	}
	// 对外返回的参数值
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		// 判断手机号码是否正确，过滤外国号码等
		if (PhoneUtils.filterIssueNumber(caller) && PhoneUtils.filterIssueNumber(called)) {
		    // 查询应用信息
		    AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		    // 判断app信息是否为空
		    if (appExtendBean != null) {
			// 根据cust_account查询账号信息
			AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			// 判断账号信息是否找到
			if (accountBean != null) {
			    // 验证秘钥信息
			    if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				// 获取语音短信能力类型标识
				String abilityType = AbilityTypeEnum.DIAL.getKey();
				// 到运营平台验证账号相关信息--判断是否可以通话
				if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, abilityType)) {
				    // 用于发起通话用service
				    IConferenceDialService conferenceDialService = new ConferenceDialServiceImpl();
				    // 进入通话业务--此业务中完成了发起通话接口以及发起通话后的一些数据存储，如存储会议信息、存储用户信息、存储
				    object = conferenceDialService.doDial(appExtendBean, accountBean, caller, called, ext_terminalCode, isRecord, displayNbrMode, displayNbr,
					    usePlatNbr);
				} else {
				    object.put("sessionId", "");
				    object.put("displayNbr", "");
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "参数sign错误");
				object.put("code", "0001");
				object.put("sessionId", "");
				object.put("displayNbr", "");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "计费账号不存在");
			    object.put("code", "0002");
			    object.put("sessionId", "");
			    object.put("displayNbr", "");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的应用标识");
			object.put("code", "0007");
			object.put("sessionId", "");
			object.put("displayNbr", "");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "号码格式错误");
		    object.put("code", "0004");
		    object.put("sessionId", "");
		    object.put("displayNbr", "");
		}
	    }
	} catch (Exception e) {
	    log.info("********发起两方会话失败**********");
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("code", "0401");
	    object.put("describe", "两方通话异常");
	    object.put("errorMsg", "错误:" + e.getMessage());
	    object.put("sessionId", "");
	    object.put("displayNbr", "");

	}
	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "app_key:" + app_key + "|ext_terminalCode:" + ext_terminalCode + "|cust_account:" + cust_account + "|caller:" + caller + "|called:" + called;
	request_msg = request_msg + "|timestamp:" + timestamp + "|sign:" + sign + "|displayNbr:" + displayNbr + "|displayNbrMode:" + displayNbrMode + "|isRecord:" + isRecord
		+ "|usePlatNbr:" + usePlatNbr;
	this.logService.logInterface(during, "dialV4", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(),
		caller);

	object.remove("errorMsg"); // 数据库日志存储失败详细描述
	String data = "";
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}

	return returnData(data);
    }

    /**
     * 结束两人会话
     * 
     * @return
     */
    @Override
    public String dialStop() {
	log.info("load OpenAbilityDIALController.dialStop V4 结束两人会话 ");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// 请求参数
	String sessionId = (String) this.getRequest().getParameter("sessionid");
	String[] sessionidStr = { "sessionid", sessionId, "50", "0", "str" };
	checkParamlist.add(sessionidStr);
	// 工作圈适用参数
	String callback = this.getRequest().getParameter("callback");

	JSONObject object = new JSONObject();
	try { // 判断传输的参数是否正确
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		// 结束双人通话业务
		IConferenceDialEndService conferenceDialEndService = new ConferenceDialEndServiceImpl();
		// 进行业务处理
		object = conferenceDialEndService.doDialEnd(sessionId);
	    }
	} catch (Exception e) {
	    log.info("********结束电话会议失败**********");
	    object.put("result", "-1");
	    object.put("code", "0402");
	    object.put("errorMsg", "错误:" + e.getMessage());
	    object.put("describe", "结束两方通话失败");
	}

	// 接口调用结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "结束IMS双人通话?sessionId=" + sessionId;
	this.logService.logInterface(during, "dialStopV4", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest()
		.getRemoteAddr(), null);

	object.remove("errorMsg"); // 数据库日志存储失败详细描述
	String data = "";
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}

	return returnData(data);
    }

}
